import Ionicons from "@expo/vector-icons/Ionicons";
import { useRouter } from "expo-router";
import React, { useEffect, useRef, useState } from "react";
import {
  FlatList,
  InteractionManager,
  KeyboardAvoidingView,
  Platform,
  SafeAreaView,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from "react-native";

const mockData = [
  { id: "1", name: "BBC Learning English" },
  { id: "2", name: "TED Talk - Climate" },
  { id: "3", name: "VOA News" },
];

export default function SearchScreen() {
  const router = useRouter();
  const [query, setQuery] = useState("");
  const inputRef = useRef<TextInput>(null);

  useEffect(() => {
    const timer = InteractionManager.runAfterInteractions(() => {
      inputRef.current?.focus();
    });

    return () => timer.cancel();
  }, []);

  const filtered = mockData.filter((item) =>
    item.name.toLowerCase().includes(query.toLowerCase())
  );

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: "#fff" }}>
      <KeyboardAvoidingView
        behavior={Platform.OS === "ios" ? "padding" : undefined}
        style={{ flex: 1 }}
      >
        {/* 顶部搜索栏 */}
        <View
          style={{
            flexDirection: "row",
            alignItems: "center",
            padding: 12,
            borderBottomWidth: 1,
            borderBottomColor: "#e0e0e0",
          }}
        >
          <TouchableOpacity
            onPress={() => router.back()}
            style={{ padding: 6 }}
          >
            <Ionicons name="chevron-back" size={24} color="#333" />
          </TouchableOpacity>
          <TextInput
            ref={inputRef}
            placeholder="搜索音频"
            value={query}
            onChangeText={setQuery}
            style={{
              flex: 1,
              marginLeft: 20,
              padding: 8,
              borderRadius: 8,
              fontSize: 24,
            }}
          />
        </View>

        {/* 搜索结果列表 */}
        <FlatList
          data={filtered}
          keyExtractor={(item) => item.id}
          keyboardShouldPersistTaps="always" // 避免点击时自动收键盘
          renderItem={({ item }) => (
            <TouchableOpacity
              style={{
                padding: 16,
                borderBottomWidth: 1,
                borderBottomColor: "#eee",
              }}
              onPress={() => {
                // do something with selection
              }}
            >
              <Text style={{ fontSize: 16 }}>{item.name}</Text>
            </TouchableOpacity>
          )}
        />
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}
